<?php

namespace App\Http\Controllers\Admin\Goods;

use App\Exceptions\ShopException;
use App\Services\Admin\Goods\CategoryService;
use Exception;
use Illuminate\Http\JsonResponse;

class CategoryController extends BaseGoodsController
{
    protected CategoryService $categoryService;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->categoryService = $this->loadService('Admin\Goods\CategoryService');
    }

    /**
     * 分类列表
     * @return JsonResponse
     * @throws Exception
     */
    public function list(): JsonResponse
    {
        $list = $this->categoryService->list($this->params);
        return outputJsonResult($list);
    }

    /**
     * 分类详情
     * @return JsonResponse
     * @throws ShopException
     */
    public function detail(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1'
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $detail = $this->categoryService->detail($this->params);
        return outputJsonResult($detail);
    }

    /**
     * 创建分类
     * @return JsonResponse
     * @throws Exception
     */
    public function create(): JsonResponse
    {
        $rule = [
            'title' => 'required|string',
            'imgUrl' => 'required|string'
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->categoryService->create($this->params);
        return outputJsonResult();
    }

    /**
     * 更新分类
     * @return JsonResponse
     * @throws Exception
     */
    public function update(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1',
            'title' => 'required|string',
            'imgUrl' => 'required|string'
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->categoryService->update($this->params);
        return outputJsonResult();
    }

    /**
     * 删除分类
     * @return JsonResponse
     * @throws Exception
     */
    public function delete(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1'
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->categoryService->delete($this->params);
        return outputJsonResult();
    }
}
